#!/bin/bash

set -e

BUILD_DIRECTORY="$1"
APP_CONTENTS_DIRECTORY="$2"
LINUX_ASSETS_DIRECTORY="$3"

RPM_BUILD_ROOT=~/rpmbuild
ARCH=`uname -m`

# Work around for `uname -m` returning i686 when rpmbuild uses i386 instead
if [ "$ARCH" = "i686" ]; then
	ARCH="i386"
fi

# rpmdev-setuptree
mkdir -p $RPM_BUILD_ROOT/BUILD
mkdir -p $RPM_BUILD_ROOT/SPECS
mkdir -p $RPM_BUILD_ROOT/RPMS

cp -r "$APP_CONTENTS_DIRECTORY/"* "$RPM_BUILD_ROOT/BUILD"
cp -r "$LINUX_ASSETS_DIRECTORY/icons" "$RPM_BUILD_ROOT/BUILD"
cp "$BUILD_DIRECTORY/mailspring.spec" "$RPM_BUILD_ROOT/SPECS"
cp "$BUILD_DIRECTORY/mailspring.desktop" "$RPM_BUILD_ROOT/BUILD"
cp "$BUILD_DIRECTORY/mailspring.appdata.xml" "$RPM_BUILD_ROOT/BUILD"

rpmbuild -ba "$BUILD_DIRECTORY/mailspring.spec"
cp $RPM_BUILD_ROOT/RPMS/$ARCH/mailspring-*.rpm "$BUILD_DIRECTORY"

rm -rf "$RPM_BUILD_ROOT"
